package org.zdd.bookstore.model.service.impl;

import org.zdd.bookstore.common.utils.BSResultUtil;
import org.zdd.bookstore.exception.BSException;
import org.zdd.bookstore.model.dao.UserMapper;
import org.zdd.bookstore.model.entity.User;
import org.zdd.bookstore.model.service.IMailService;
import org.zdd.bookstore.vo.UserVo;
import org.zdd.bookstore.vo.UserVoToUser;
import org.zdd.bookstore.web.controller.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * 发邮件服务
 */
@Service
public class MailServiceImpl implements IMailService {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private UserMapper userMapper;

    @Value("${mail.fromMail.addr}")
    private String from;


    @Override
    @Async//异步发邮件
    public void sendHtmlMail(String to, String subject, String content) throws Exception {

        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(content,true);

        try {
            mailSender.send(message);
            logger.info("邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送邮件时发生异常！", e);
            throw new BSException("发送邮件时发生异常！");
        }
    }

    @Override
    @Async//异步发邮件
    public void sendSimpleMail(String to, String subject, String content) throws Exception {

        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        try {
            mailSender.send(message);
            logger.info("简单邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常！", e);
            throw new RuntimeException("发送简单邮件时发生异常！");
        }
    }

    /**
     * 6位数验证码
     *
     * @return
     */
    @Override
    public String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    /**
     * 判断用户和邮箱是否存在
     *
     * @param user
     * @return
     */
    @Override
    public String selectUserByUsername(User user) {
        User user1 = userMapper.selectUserByUsername(user);
        return user1 != null ? "SUCCESS" : "ERROR";
    }

    /**
     * 找回密码的发送验证码
     * @param email
     * @param session
     * @return
     */
    @Override
    public Boolean sendMimeMail2(String email, HttpSession session) {
        try {
            //邮箱信息
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            //主题
            mailMessage.setSubject("找回密码");
            //生成随机数
            String code = randomCode();
            System.out.println("code = " + code);
            //将随机数放置到session中
            session.setAttribute("email", email);
            session.setAttribute("code", code);
            //内容
            mailMessage.setText("找回密码的验证码是：" + code);
            //发给谁
            mailMessage.setTo(email);
            //你自己的邮箱
            mailMessage.setFrom(from);
            //发送
            mailSender.send(mailMessage);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 修改密码
     * @param userVo
     * @param session
     * @return
     */
    @Override
    public Boolean updateUserPassword(UserVo userVo, HttpSession session) {
        //获取session中的验证信息
        String email = (String) session.getAttribute("email");
        String code = (String) session.getAttribute("code");
        //获取表单中的提交的验证信息
        String voCode = userVo.getCode();
        //如果email数据为空，或者不一致，注册失败
        if (email == null || email.isEmpty()) {
            return false;
        } else if (!voCode.equals(code)) {
            return false;
        }

        //保存数据
        User user = UserVoToUser.toUser(userVo);

        //将数据写入数据库
        Integer result = userMapper.updateUserPassword(user);
        if (result == null){
            BSResultUtil.build(400,"保存失败");
        }
        //跳转成功页面
        return true;
    }
}
